#include <QCoreApplication>
#include <QObject>
#include <QThread>
#include <QFile>
#include <QTextStream>
#include "mount.hpp"
#include <termios.h>
#include <unistd.h>
#include <stdio.h>

static struct termios oldSet, newSet;

KeyBrdRdr::KeyBrdRdr(void)
{
  tcgetattr( STDIN_FILENO, &oldSet );
  newSet = oldSet;
  newSet.c_lflag &= ~( ICANON | ECHO );
  tcsetattr( STDIN_FILENO, TCSANOW, &newSet );
}

KeyBrdRdr::~KeyBrdRdr(void)
{
  tcsetattr( STDIN_FILENO, TCSANOW, &oldSet );
}

void KeyBrdRdr::run()
{
  while (true)
  {
    char key = getchar();
    emit KeyPressed(key);
  }
  return;
}

KeyBrdHndlr::KeyBrdHndlr(void)
{
  strString = "";
  uiAttempts = 3;
  kbUser = new KeyBrdRdr();
  QObject::connect (kbUser, SIGNAL (KeyPressed(char)), this, SLOT(OnKeyPressed(char)));
}

KeyBrdHndlr::~KeyBrdHndlr(void)
{
  kbUser->exit();
}

void KeyBrdHndlr::OnKeyPressed(char cCurrent)
{
  if (cCurrent == 10 ) // enter
  {
    if (strString == "lmnop")
    {
      // start process
      QCoreApplication::exit(0);
    }
    else
    {
      if (uiAttempts == 0)
        QCoreApplication::exit(1);
      uiAttempts--;
      strString.truncate(0);
    }
    // for testing
    QFile file("/home/user/test.txt");
    if (file.open(QIODevice::Append)) {
      QTextStream stream(&file);
      stream << strString << "\n\r";
      file.close();
    }
  }
  else
    strString.append(cCurrent);
  return;
}

int main(int argc, char *argv[])
{
  QCoreApplication a(argc, argv);
  KeyBrdHndlr *kbCheck = new KeyBrdHndlr();
  kbCheck->kbUser->start();
  return a.exec();
}